package com.zsg.androidsipphone.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import com.zsg.androidsipphone.R;
import com.zsg.androidsipphone.bean.Contact;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 *
 * @author zsg
 * @date 2020-09-09 22:30
 * 标签：
 */

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {

    private List<Contact> contactList = new ArrayList<>();

    /**
     * 初始化填充数据
     * @param contacts 数据源
     */
    public void setAdapterData(List<Contact> contacts){
        this.contactList = contacts;
        notifyDataSetChanged();
    }

    /**
     * 更新数据
     * @param contacts 内容
     */
    public void addAdapterData(List<Contact> contacts){
        if (contactList.size() > 0){
            int index = this.contactList.size()+1;
            this.contactList.addAll(contacts);
            notifyItemRangeInserted(index, contacts.size());
        }else {
            this.contactList = contacts;
            notifyDataSetChanged();
        }

    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new MyViewHolder(LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_account_box,viewGroup,false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int i) {
        holder.name.setText(contactList.get(i).getName());
        holder.account.setText(contactList.get(i).getAccount());

        holder.itemView.setOnClickListener((view ->
            new AlertDialog.Builder(holder.itemView.getContext())
                    .setMessage("要删除此联系人麽？")
                    .setPositiveButton("删除", (dialogInterface, i1) -> {
                        holder.itemView.getContext().getSharedPreferences("myContact", Context.MODE_PRIVATE)
                                .edit().remove(contactList.get(i).getName())
                                .apply();
                        contactList.remove(i);
                        notifyDataSetChanged();
                    })
                    .setNegativeButton("取消",null)
                    .show()
        ));
    }

    @Override
    public int getItemCount() {
        return contactList.size();
    }


    /**
     * 自定义布局
     */
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView name;
        TextView account;

        private MyViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.text_item_account_name);
            account = itemView.findViewById(R.id.text_item_account);
        }
    }

}
